﻿using Decisions.HL7.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Decisions.HL7
{
    public class HL7ParserOptions
    {
        public bool FailOnFormatErrors { get; set; }
        public bool CleanAndTrimLineStarts { get; set; }
        public bool AllowExtraSegments { get; set; }

        public ParserMode ParserMode { get; set; }

        public char FieldSep { get; set; }
        public char ComponentSep { get; set; }
        public char FieldRepeatSep { get; set; }
        public char EscapeChar { get; set; }
        public char SubComponentSep { get; set; }

        public bool OutputEmptyStringAsNull { get; set; }

        public Decisions.HL7.Message.HL7Version Version { get; set; }

        public HL7ParserOptions()
        {
            SetAllDefaults();
        }

        private void SetAllDefaults()
        {
            // Default the seps.
            FieldSep = HL7ParserConstants.DEFAULT_FIELD_SEP;
            ComponentSep = HL7ParserConstants.DEFAULT_COMPONENT_SEP;
            FieldRepeatSep = HL7ParserConstants.DEFAULT_FIELD_REPEAT;
            EscapeChar = HL7ParserConstants.DEFAULT_ESCAPE;
            SubComponentSep = HL7ParserConstants.DEFAULT_SUBCOMP_SEP;

            // Default to Strict Parsing Mode
            ParserMode = Parser.ParserMode.Strict;

            Version = Message.HL7Version.v27;

            OutputEmptyStringAsNull = true;
        }

        public HL7ParserOptions(bool failOnFormatErrors, bool cleanAndTrimLineStarts, bool allowExtraSegments) : this()
        {
            this.AllowExtraSegments = allowExtraSegments;
            this.FailOnFormatErrors = failOnFormatErrors;
            this.CleanAndTrimLineStarts = cleanAndTrimLineStarts;
        }

        public HL7ParserOptions(DataTypes.AbstractMessage abstractMessage)
        {
            if (abstractMessage != null && abstractMessage.MSH != null && string.IsNullOrEmpty(abstractMessage.MSH.FieldSeparator) == false)
            {
                Version = HL7Parser.GetVersionFromMSH(abstractMessage.MSH);
                FieldSep = abstractMessage.MSH.FieldSeparator[0];
                ComponentSep = abstractMessage.MSH.EncodingCharacters[0];
                SubComponentSep = abstractMessage.MSH.EncodingCharacters[3];
                FieldRepeatSep = abstractMessage.MSH.EncodingCharacters[1];
                EscapeChar = abstractMessage.MSH.EncodingCharacters[2];
            }
            else {
                SetAllDefaults();
            }

        }

        public static HL7ParserOptions DefaultHL7ParserOptions = new HL7ParserOptions(true, true, true);


        internal string GetEncodingChars()
        {
            return string.Format("{0}{1}{2}{3}", ComponentSep, FieldRepeatSep, EscapeChar, SubComponentSep);
        }
    }
}
